package top.lemos.navib;

import android.app.DialogFragment;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import static java.lang.Math.min;


/**
 * Created by Sonp on 2017/5/7.
 */

public class PictureFragment extends DialogFragment {
    public static final String EXTRA_ID="picture_id";
    private Integer mPictureId;
    public static PictureFragment newInstance(Integer pictureId) {

        Bundle args = new Bundle();
        args.putInt(EXTRA_ID,pictureId);
        PictureFragment fragment = new PictureFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private boolean isPortrait(){
        return getActivity().getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPictureId=(Integer) getArguments().getInt(EXTRA_ID);
        setStyle(DialogFragment.STYLE_NORMAL,R.style.AppTheme_NoActionBar);
    }

    private  Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v=getActivity().getLayoutInflater().inflate(R.layout.dialog_picture,null);
        Bitmap bitmap=BitmapFactory.decodeResource(getResources(),mPictureId,null);

        ImageView picture=(ImageView)v.findViewById(R.id.big_picture);
        if((bitmap.getWidth()<bitmap.getHeight())^isPortrait()){
            bitmap=rotaingImageView(90,bitmap);
        }
        picture.setImageBitmap(bitmap);
        picture.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        return v;
    }
}
